//
//  DetailViewController.m
//  SexColorReading
//
//  Created by 殷殷明静 on 16/9/12.
//  Copyright © 2016年 LyMjy. All rights reserved.
//

#import "RelevantFirstVC.h"
#import "ContentTableViewCell.h"
#import "YMJMacro_h.h"
#import "UIView+YMJ_view.h"
#import "UIImageView+WebCache.h"
#import "AFNetworking.h"
#import "DetailModel.h"
#import "AtlasItemDTO.h"
#import "AtlasRelevantDTO.h"
#import "SelfSizeTool.h"
#import "MoreImageCollectionCollectionViewCell.h"
#import "RelevantSecondVC.h"
#define COLOR [UIColor colorWithRed: 37 / 255.0 green:37 / 255.0 blue:37 / 255.0 alpha:100];

@interface RelevantFirstVC ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong) NSMutableArray *moreArray;
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UIScrollView *bottomScrollView;
@property (nonatomic, strong) UIScrollView *zoomScrollView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UICollectionView *collect;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, assign) CGFloat lastContentOffSet;
@property (nonatomic, strong) UIImageView *placeHolderView;
@end

@implementation RelevantFirstVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    // 获得viewController
    self.view.backgroundColor = COLOR
    [self initNavigationLeftButton];
    [self createData];
}
- (void)createData {
    _placeHolderView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"imagePlaceHolder"]];
    _placeHolderView.center = CGPointMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 64);
    [self.view addSubview:_placeHolderView];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    // 请求头
    [manager.requestSerializer setValue:@"Dalvik/1.6.0 (Linux; U; Android 4.2.1; R823T Build/JOP40D) Liuda/2.2.0 (agent:s;channel:360;credential:e1MxMDEwMDAxMDF9LXsjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIzg2MzMzMTAyODY3NDU0Mn0teyMjIyMjIyMxNDczMTU1OTc5ODA3LTQzNTkzYTY2M2R9QDE0NzI0MTc2MzEzMDE=;deviceId:863331028674542;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:4.2.1;idfa:null)" forHTTPHeaderField:@"User-Agent"];
    [manager.requestSerializer setValue:@"api.9liuda.com" forHTTPHeaderField:@"Host"];
    [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    NSString *URL = [NSString stringWithFormat:@"http://211.151.51.80/v1/message/atlas?messageId=%@&messageType=%@&parentType=%@&parentId=null&categoryIds=%@",_messageId,_messageType,_parentType,_categoryIds];
    [manager GET:URL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject;
        DetailModel *detailModel = [DetailModel modelWithDic:dic];
        _imageArray = [NSMutableArray arrayWithArray:detailModel.data.atlasItemDTOCollection];
        _moreArray = [NSMutableArray arrayWithArray:detailModel.data.atlasRelevantDTOCollection];
        [self createBottomScrollerView];
        [self createContentTableView];
        [self createCollectionView];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
    
}
- (void)createCollectionView {
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake( _imageArray.count * SCREEN_WIDTH + 5, 44, SCREEN_WIDTH - 10, SCREEN_HEIGHT - 64)];
    [_bottomScrollView addSubview:bottomView];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(155, 135);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    _collect = [[UICollectionView alloc] initWithFrame:bottomView.bounds collectionViewLayout:flowLayout];
    [bottomView addSubview:_collect];
    _collect.backgroundColor = [UIColor clearColor];
    _collect.delegate = self;
    _collect.dataSource = self;
    [_collect registerNib:[UINib nibWithNibName:@"MoreImageCollectionCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"2"];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 6;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    AtlasRelevantDTO *dto = _moreArray[indexPath.row];
    MoreImageCollectionCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"2" forIndexPath:indexPath];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:dto.image]];
    cell.label.text = dto.title;
    return cell;
}
- (void)createContentTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 450 - 64 - 5, SCREEN_WIDTH, 150) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerNib:[UINib nibWithNibName:@"ContentTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"1"];
    _tableView.backgroundColor = [UIColor clearColor];
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    RelevantSecondVC *relevantVC = [RelevantSecondVC new];
    AtlasRelevantDTO *dto = _moreArray[indexPath.row];
    relevantVC.messageId = dto.messageId;
    relevantVC.categoryIds = dto.categoryIds;
    relevantVC.infomation = dto.title;
    relevantVC.parentId = dto.parentId;
    relevantVC.parentType = dto.parentType;
    relevantVC.messageType = dto.messageType;
//    [self setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:relevantVC animated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    AtlasItemDTO *dto = _imageArray[indexPath.row];
    CGFloat height = [SelfSizeTool selfSizeHeightWithString:dto.descriptionTitle width:282 font:[UIFont fontWithName:@"FZKaTong-M19S" size:13]] + [SelfSizeTool selfSizeHeightWithString:_infomation width:282 font:[UIFont fontWithName:@"FZKaTong-M19S" size:13]]+ 40;
    if (height < 120) {
        return 150;
    } else {
        return height + 50;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AtlasItemDTO *dto = _imageArray[indexPath.row];
    ContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"1"];
    cell.contentView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    cell.countLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row + 1];
    cell.titleLabel.text = [NSString stringWithFormat:@"%ld/ %ld %@",indexPath.row + 1,_imageArray.count,_infomation];
    cell.contentLabel.text = dto.descriptionTitle;
    return cell;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH ;
    if (index <= _imageArray.count - 1) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        ContentTableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
//        cell.countLabel.text = [NSString stringWithFormat:@"%ld",index + 1];
        cell.titleLabel.text = [NSString stringWithFormat:@"%ld/ %ld %@",index + 1,_imageArray.count,_infomation];
        _tableView.alpha = 1;
    } else {
        _tableView.alpha = 0;
    }
    
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.x <= (_imageArray.count - 1) * SCREEN_WIDTH) {
        if (scrollView.contentOffset.x - _lastContentOffSet < 0) {
            _tableView.alpha = 1 + (scrollView.contentOffset.x - _lastContentOffSet ) / SCREEN_WIDTH ;
        } else {
            _tableView.alpha = 1 - (scrollView.contentOffset.x - _lastContentOffSet ) / SCREEN_WIDTH ;
        }
        if (_tableView.alpha == 0) {
            _tableView.alpha = 1;
        }
    } else  {
        _tableView.alpha = 0;
    }
    
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    _lastContentOffSet = scrollView.contentOffset.x;
}
- (void)createBottomScrollerView {
    
    /*底部ScrollerView */
    
    _bottomScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    [self.view addSubview:_bottomScrollView];
    _bottomScrollView.backgroundColor = [UIColor clearColor];
    _bottomScrollView.contentSize = CGSizeMake(SCREEN_WIDTH * (_imageArray.count + 1), 0);
    _bottomScrollView.pagingEnabled = YES;
    _bottomScrollView.delegate = self;
    _bottomScrollView.showsVerticalScrollIndicator = NO;
    _bottomScrollView.showsHorizontalScrollIndicator = NO;
    for (int i = 0; i < _imageArray.count; i++) {
        
        /*缩放ScrollerView */
        
        _zoomScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(i * SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        _zoomScrollView.contentSize = CGSizeMake(0, 0);
        _zoomScrollView.delegate = self;
        
        /*缩放比例 */
        _zoomScrollView.maximumZoomScale = 2.0;
        _zoomScrollView.minimumZoomScale = 0.5;
        
        _zoomScrollView.backgroundColor = [UIColor clearColor];
        [_bottomScrollView addSubview:_zoomScrollView];
        /*缩放的图片*/
        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        _imageView.backgroundColor = [UIColor clearColor];
        _imageView.tag = 10000 + i;
        [_zoomScrollView addSubview:_imageView];
        AtlasItemDTO *dto = _imageArray[i];
        NSURL *url = [NSURL URLWithString:dto.image];
        [_imageView sd_setImageWithURL:url placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (image.size.height < image.size.width) {
                UIImageView *images = (UIImageView *)[self.view viewWithTag:10000 + i];
                images.frame = CGRectMake(0, 100, SCREEN_WIDTH, 300 - 20);
            }
            
        }];
        
        
    }
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    
    return scrollView.subviews.firstObject;
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    if (scrollView.zoomScale < 1.0) {
        scrollView.subviews.firstObject.center = CGPointMake(SCREEN_WIDTH / 2, (SCREEN_HEIGHT - 64) / 2);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
// 自定义导航栏样式
- (void)initNavigationLeftButton {
    _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    _backBtn.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_backBtn];
    _backBtn.frame = CGRectMake(20, 20, 20, 20);
    [_backBtn setBackgroundImage:[UIImage imageNamed:@"Icon_jiantou"] forState:0];
    [_backBtn addTarget:self action:@selector(backToLoginAndRegisterViewController) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_backBtn];
    
    
}
// pop返回
- (void)backToLoginAndRegisterViewController {
    [self.navigationController popViewControllerAnimated:YES];
}
// 自定义导航栏shadowImage的横线
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"balckNavcBar"] forBarMetrics:0];
//    self.navigationController.navigationBar.shadowImage = [UIImage imageNamed:@"Icon_line"];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:0];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
// 根据图片url获取图片尺寸



@end
